class ZPElement extends HTMLElement {
  templateRootError(){
    throw 'Template root tag is unexpected!';
  }

  //获取html字符串根标签名
  get rootTagName(){
    const reg = /<\/.+>\s*?$/g;
    const res = this.template.match(reg);
    if (!res) this.templateRootError();
    return res[0].replace(/[<>\/\s]/g,'');
  }

  //获取html字符串根标签内容
  get rootHTML(){
    const reg = /^\s*?<[\s\S]+?>([\s\S]*)<\/.+>\s*?$/;
    const res = this.template.match(reg);
    if (!res) this.templateRootError();
    return res[1];
  }

  //渲染HTML
  render(){
    let shadow = this.attachShadow({mode: 'open'});
    if (this.style) {
      const styleNode = document.createElement('style');
      styleNode.textContent = this.style;
      shadow.append(styleNode);
    }
    if (this.template) {
      const node = document.createElement(this.rootTagName);
      node.innerHTML = this.rootHTML;
      shadow.append(node);
    }
  }

  constructor(){
    super();
    this.render();
  }
}

export default ZPElement;